<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Message\Image;
use think\Request;
use think\Env;

/**
 * 上传接口
 */
class Uploads extends Common
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $uploadPath = null;
    protected $imageName = null;
    protected $siteUrl = null;
    protected $width = null;
    protected $height = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->uploadPath = './uploads/' . date('Ymd') . '/';
        $this->imageName = time() . '.jpg';
        $this->siteUrl = Env::get('app.base_site_url');
        //缩略图宽高
        $this->width = $this->request->request('width')?$this->request->request('width'):200;
        $this->height = $this->request->request('height')?$this->request->request('height'):200;

    }

    public function UploadImage()
    {
        if (!file_exists( $this->uploadPath)) {
            mkdir($this->uploadPath, 0777, true);
        }
        $file = $this->uploadPath . $this->imageName;
        if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
            $data = $this->ThumbImage($file, $this->width, $this->height);
            $this->outputData($data);
        } else {
            $this->outputData('上传失败');
        }
    }

    public function ThumbImage($imgurl, $width, $height)
    {
        $image = \think\Image::open($imgurl);
        $date_path = './uploads/thumb/' . date('Ymd');
        if (!file_exists($date_path)) {
            mkdir($date_path, 0777, true);
        }
        $thumb_path = $date_path . '/' . $this->imageName;
        $image->thumb($width, $height)->save($thumb_path);
        $data['img'] = str_replace('./','/',$imgurl);
        $data['thumb_img'] = str_replace('./','/',$thumb_path);
        return $data;
    }
}
